package com.coincalf.web;

import com.coincalf.entity.Sms;
import com.coincalf.entity.User;
import com.coincalf.framework.enums.ResultCode;
import com.coincalf.framework.http.Response;
import com.coincalf.service.SmsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author qiang
 */
@Slf4j
@RestController
@RequestMapping("/sms")
@Api(value = "短信发送与验证", description = "短信发送与验证")
public class SmsController {

    @Autowired
    private SmsService smsService;
    @Autowired
    private CommonController commonController;

    @ApiOperation(value = "短信发送", httpMethod = "POST")
    @PostMapping("/sendTo")
    public Response sendTo(HttpServletRequest request) {
        User user = commonController.getUser(request);
        Sms sms = new Sms();
        sms.setMobile(user.getMobile());
        sms.setCountryCode(user.getCountryCode());
        if (StringUtils.isEmpty(user.getMobile())) {
            return Response.err(ResultCode.MOBILE_NOT_EMPTY);
        }
        return smsService.sendTo(sms);
    }

    /**
     * 短信验证
     *
     * @param request
     * @param code
     * @return
     */
    @ApiOperation(value = "短信验证", httpMethod = "POST")
    @PostMapping("/verify")
    public Response verify(HttpServletRequest request, String code) {
        User user = commonController.getUser(request);
        if (StringUtils.isEmpty(user.getMobile())) {
            return Response.err(ResultCode.MOBILE_NOT_EMPTY);
        }
        if (StringUtils.isEmpty(code)) {
            return Response.err(ResultCode.PARAM_ERROR);
        }
        Sms sms = new Sms();
        sms.setMobile(user.getMobile());
        sms.setContent(code);
        return smsService.verifySms(sms);
    }

}
